import {
  invoiceAllListServer,
  invoiceListServer,
  invoiceAddServer,
  invoiceEditServer,
  invoiceSendEmailServer,
  seletEinvoiceDetailServer,
} from '@/services/invoiceAssistant';
// import Taro from "@tarojs/taro";

export default {
  namespace: 'invoiceAssistant',
  state: {},
  effects: {
    *invoiceAllListModel({ payload }, { call, put }) {
      const res = yield call(invoiceAllListServer, payload);
      if (res.code === '1') {
        yield put({
          type: 'invoiceAllListData',
          payload: res.content.list,
        });
      }
    },
    *invoiceListModel({ payload }, { call, put }) {
      const res = yield call(invoiceListServer, payload);
      let arr = [];
      if (res.code === '1') {
        const enterpriseTitleResponse = res.content.enterpriseTitleResponse;
        const personalTitleResponse = res.content.personalTitleResponse;
        if (enterpriseTitleResponse.length === 0 && personalTitleResponse.length > 0) {
          arr = personalTitleResponse;
        } else if (enterpriseTitleResponse.length > 0 && personalTitleResponse.length === 0) {
          arr = enterpriseTitleResponse;
        } else {
          arr = enterpriseTitleResponse.concat(personalTitleResponse);
        }
        yield put({
          type: 'invoiceListData',
          payload: arr,
        });
      }
    },
    *invoiceAddModel({ payload }, { call }) {
      const res = yield call(invoiceAddServer, payload);
      if (res.code === '1') {
        return res;
      }

      return Promise.reject(new Error(res.message));
    },
    *invoiceEditModel({ payload }, { call }) {
      const res = yield call(invoiceEditServer, payload);
      if (res.code === '1') {
        return res;
      }

      return Promise.reject(new Error(res.message));
    },
    *invoiceSendEmailModel({ payload }, { call }) {
      const res = yield call(invoiceSendEmailServer, payload);
      if (res.code === '1') {
        return res;
      }
    },
    *seletEinvoiceDetailModel({ payload }, { call, put }) {
      const res = yield call(seletEinvoiceDetailServer, payload.id);
      if (res.code === '1') {
        const urls = res.content?.pdfUrl || '';
        res.content.urlList = urls.length > 0 ? urls.split(',') : [];
        yield put({
          type: 'seletEinvoiceDetail',
          payload: res.content,
        });
      }
    },
  },
  reducers: {
    invoiceListData(state, { payload }) {
      return { ...state, invoiceListData: payload };
    },
    invoiceAllListData(state, { payload }) {
      return { ...state, invoiceAllListData: payload };
    },
    seletEinvoiceDetail(state, { payload }) {
      return { ...state, seletEinvoiceDetail: payload };
    },
  },
};
